package com.lapi.lapiinterface.controller;

import com.lapi.lapiclientsdk.model.User;
import com.lapi.lapiclientsdk.utils.SignUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/***
 * 名称API
 *
 * @author wzhdjy
 */
@RestController
@RequestMapping("name")
public class NameController {
    @GetMapping("/")
    public String getNameByGet(String name) {
        return "GET 你的名字是" + name;
    }

    @PostMapping("/")
    public String getNameByPost(@RequestParam String name) {
        return "POST 你的名字是" + name;
    }

    @PostMapping("/josn")
    public String getUserNameByPost(@RequestBody User user, HttpServletRequest request) {
        //        获取签名
        String accessKey = request.getHeader("accessKey");
        String sign = request.getHeader("sign");
        String nonce = request.getHeader("nonce");
        String timestamp = request.getHeader("timestamp");
        String body = request.getHeader("body");
//        进行校验
        if (!accessKey.equals("wzhdjy")) {
            throw new RuntimeException("无权限");
        }
//        如果随机数不在指定范围内
        if (Long.parseLong(nonce) > 10000) {
            throw new RuntimeException("无权限");
        }
//        如果时间超过五分钟
        if (System.currentTimeMillis() / 1000 - Long.parseLong(timestamp) > 5 * 60) {
            throw new RuntimeException("无权限");
        }
        //TODO 这里的secretKey从数据库中查询
        String serverSign = SignUtils.genSign(body, "123");
        if (!serverSign.equals(sign)) {
            throw new RuntimeException("签名认证失败");
        }
//        如果校验通过，则进行操作
        return "POST 用户名字是" + user.getUserName();
    }
}
